package readwritelock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;


//  创建资源类
class myCache{

  //    创建资源map集合
  private volatile Map<String,Object>map = new HashMap<>();

//  创建读写锁对象
  private ReadWriteLock readWriteLock  = new ReentrantReadWriteLock();

  //    创建方法
  public void put(String key,Object object){

//    添加写锁
    readWriteLock.writeLock().lock();

    System.out.println(Thread.currentThread().getName() + " 正在写操作" + key);
//    暂停一会
    try {
      TimeUnit.MICROSECONDS.sleep(300);
      map.put(key,object);
      System.out.println(Thread.currentThread().getName() + " 写完了" + key);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }finally {
//      释放写锁
      readWriteLock.writeLock().unlock();
    }


  }

  public Object get(String key){

//    添加读锁
    readWriteLock.readLock().lock();

    Object result = null;

    System.out.println(Thread.currentThread().getName() + " 正在读取操作" + key);

    try {
      TimeUnit.MILLISECONDS.sleep(300);
      result = map.get(key);
      System.out.println(Thread.currentThread().getName() + " 取完了" + key);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }finally {
//      释放读锁
      readWriteLock.readLock().unlock();
    }


    return result;
  }
}

public class ReadWriteLockDemoII {

//  创建多线程
  public static void main(String[] args) {

    myCache cache = new myCache();

//    创建线程放数据
    for (int i = 1; i <= 5; i++) {
      final int num = i;
      new Thread(()->{
        cache.put(num+"",num+"");
      },String.valueOf(i)).start();
    }
//    创建线程取数据
    for (int i = 1; i <= 5; i++) {
      final int num = i;
      new Thread(()->{
        cache.get(num+"");
      },String.valueOf(i)).start();
    }


  }
}
